package main

import (
	"net/http"
	"sync"

	"github.com/gin-gonic/gin"
)

// 声明全局变量
var (
	urlStore = make(map[string]string)
	mutex    sync.RWMutex
)

func shortenURL(c *gin.Context) {

	originalUrl := c.PostForm("url")
	if originalUrl == "" {
		c.JSON(400, gin.H{"error": "Invalid JSON"})
		return
	}

	// 生成短链接
	shortURL := generateShortURL()
	mutex.Lock()
	urlStore[shortURL] = originalUrl
	mutex.Unlock()
	c.JSON(200, gin.H{"short_url": shortURL})

}

func redirectURL(c *gin.Context) {

	shortCode := c.Param("shorturl")

	// 读锁定
	mutex.RLock()
	originalURL, ok := urlStore[shortCode]
	mutex.RUnlock()
	if !ok {
		c.JSON(404, gin.H{"error": "Short URL not found"})
		return
	}

	c.Redirect(http.StatusFound, originalURL)
}
